<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="登陆账号" prop="account">
        <el-input v-model="queryParams.account" placeholder="登陆账号" clearable style="width: 150px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="手机号码" clearable style="width: 150px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="邮箱账号" prop="email">
        <el-input v-model="queryParams.email" placeholder="邮箱账号" clearable style="width: 150px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="staffAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="data.tableList">
      <el-table-column label="登录名称" align="center" prop="login_name" :show-overflow-tooltip="true" />
      <el-table-column label="员工工号" align="center" prop="employeeNo" :show-overflow-tooltip="true" />
      <el-table-column label="姓名" align="center" prop="real_name" :show-overflow-tooltip="true" />
      <el-table-column label="手机号" align="center" prop="phone" :show-overflow-tooltip="true" />
      <el-table-column label="邮箱地址" align="center" prop="email" :show-overflow-tooltip="true" />
      <el-table-column label="所属部门" align="center" prop="updateTime" />
      <el-table-column label="成员角色" align="center" prop="updateTime" />
      <el-table-column label="最后登录" align="center" prop="updateTime" :show-overflow-tooltip="true" />
      <el-table-column label="是否启用" align="center"
        ><template #default="scope">
          <el-switch v-model="scope.row.status" @change="handleChange(scope.row)" />
        </template>
        <!--  -->
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-tooltip content="管理机构角色" placement="top">
            <el-button link type="primary" icon="Setting" @click="handleAddTable(scope.row)" v-hasPermi="['tool:gen:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleEditTable(scope.row)" v-hasPermi="['tool:gen:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tool:gen:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page_count" v-model:limit="queryParams.page_size" @pagination="getList" />

    <!-- 添加机构角色 -->
    <el-dialog :title="organ.title" v-model="organ.open" width="65%" top="5vh" append-to-body :center="true" align-center @close="onConcel">
      <template #header>
        <div class="my-header">
          <h4>管理机构角色</h4>
          <el-button @click="addList"> 新增 </el-button>
        </div>
      </template>
      <div>
        <h4 v-show="orgList.length > 0">已有角色</h4>
        <div class="list-style" v-for="(item, index) in orgList" :key="index">
          <span> 机构名称：</span><el-input v-model="item.orgName" disabled style="width: 210px" />&nbsp;<span class="mg-left"> 所属角色：</span>
          <div class="box">
            <span v-for="(val, i) in item.child" :key="i" class="span-right">{{ val.roleName }}</span>
          </div>
          &nbsp;
          <el-button @click="onEditRole(item)">编辑</el-button>
        </div>
      </div>
      <div>
        <h4 v-show="accList.length > 0">新增角色</h4>
        <el-row v-for="(item, index) in accList" :key="index">
          <el-col :span="7">
            <el-form-item label="机构名称" maxlength="11">
              <el-tree-select v-model="item.orgName" :data="state.data" check-strictly @node-click="handleNodeClick" :render-after-expand="false" :props="defaultProps" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属角色">
              <el-select v-model="item.role"> <el-option v-for="val in state.options" :key="val.id" :label="val.name" :value="val.id" /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :span="1">
            <el-button @click="delList(index, item)">删除</el-button>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="onConfirm()"> 确定 </el-button>
          <el-button @click="onConcel">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑机构角色 -->
    <el-dialog :title="edit.title" v-model="edit.open" width="40%" top="5vh" append-to-body :center="true" align-center>
      <div>
        <div class="list-style">
          机构名称:
          <el-tree-select v-model="editList.orgName" :data="state.data" check-strictly @node-click="handleNodeClick" :render-after-expand="false" :props="defaultProps" />
        </div>
        <div class="list-style" v-for="(item, index) in editList.child" :key="index">
          所属角色:
          <el-select v-model="item.roleName" @change="onChange" @click="onClick(item, index)" @visible-change="onhandle">
            <el-option v-for="val in state.options" :key="val.id" :label="val.name" :value="val.id" />
          </el-select>
          <el-button @click="onModif(item)" class="btn">修改</el-button>
          <el-button type="primary" @click="onDelete(item)"> 删除 </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 新增成员 -->
    <el-dialog :title="dialogTitle" v-model="addDialog" width="600px" append-to-body>
      <el-form ref="addRef" :model="staffForm" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="16">
            <el-form-item label="登录名称" prop="account">
              <el-input v-model="staffForm.account" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="登录密码" type="passwd">
              <el-input v-model="staffForm.passwd" type="password" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="手机号" prop="phone" maxlength="11">
              <el-input v-model="staffForm.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="员工工号" prop="employeeNo">
              <el-input v-model="staffForm.employeeNo" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="成员姓名" prop="name">
              <el-input v-model="staffForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="staffForm.email" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="允许登录">
              <el-switch v-model="staffForm.status" inline-prompt active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="onSubmit"> 确定 </el-button>
          <el-button @click="addDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Gen">
import { accountList, editAccount, delAccount, listByAccId, getAcconutList, addAccountRoles, queryRolesByOrgId, addAccount, modifyAccount, modifyAccountRoles, delAccountRole } from "@/api/role";
import router from "@/router";
import { ElMessageBox, ElMessage, ElLoading } from "element-plus";
import { queryOrgTree } from "@/api/org";
import { ref } from "vue";

const route = useRoute();
const { proxy } = getCurrentInstance();

const state = reactive({
  data: [],
  list: [],
  options: [],
  haveOptions: [], //已有角色
  editIds: [],
});

const defaultProps = {
  children: "childs",
  label: "orgName",
  value: "id",
};
const num = ref("");
const isDisabled = ref(true);
const dialogTitle = ref("");
const addDialog = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const tableNames = ref([]);
const dateRange = ref([]);
const uniqueId = ref("");
const value1 = ref(true);
const isTrue = ref(false); //编辑修改记录
const edit_id = ref(""); //未修改前的id
const addStatus = ref(null); //1-新增

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    phone: "", //手机号
    account: undefined, //登录账号
    email: undefined, //邮箱
  },

  tableList: [],
  organ: {
    title: "选择机构角色", //
    open: false, //
    orgName: "",
    orgName1: "",
    role: "",
    role1: "",
    checked1: false,
    checked1: false,
    id: "", //当前被修改权限人员的ID
  },
  staffForm: {
    id: "",
    type: "", //1-添加2-编辑
    account: "", //账号
    name: "", //姓名
    phone: "", //手机号
    employeeNo: "", //员工工号
    status: false, //是否允许登录 1-允许2-不允许
    email: "", //邮箱
    passwd: "", //密码
    orgName: "", //机构名称
    role: "", //角色
  },
  accList: [], //新增角色列表
  orgList: [], //已有机构列表
  edit: {
    title: "编辑机构角色",
    open: false,
  },
  editList: [],
});

const rules = reactive({
  account: [{ required: true, message: "请填写账号", trigger: "blur" }],
  name: [
    {
      required: true,
      message: "请填写姓名",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
      message: "请填写邮箱",
      trigger: "blur",
    },
  ],

  passwd: [
    {
      required: true,
      message: "请填写密码",
      trigger: "blur",
    },
  ],
  employeeNo: [
    {
      required: true,
      message: "请填写员工号",
      trigger: "blur",
    },
  ],
});

const { queryParams, organ, staffForm, accList, orgList, edit, editList, delRole } = toRefs(data);

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

//添加事件
function staffAdd() {
  proxy.resetForm("addRef");

  staffForm.value.type = 1;
  dialogTitle.value = "添加成员";
  staffForm.value.account = "";
  staffForm.value.name = "";
  staffForm.value.phone = "";
  staffForm.value.email = "";
  staffForm.value.passwd = "";
  addDialog.value = true;
}

function addList() {
  addStatus.value = 1;
  accList.value.push({
    orgName: "",
    role: "",
  });
}

function delList(i, item) {
  accList.value.splice(i, 1);
  console.log(item, "itemitem");
}

//对已有角色进行编辑展示弹窗
function onEditRole(item) {
  edit.value.open = true;
  editList.value = item;
  console.log(item, "编辑角色");
  getRolesOrgId(item.orgId);
}

function onhandle(val) {
  console.log(val, "wwwwww");
  if (!val) {
    if (num.value == edit_id.value) {
    }
  }
}

//对已有角色进行更改是触发
function onChange(val) {
  num.value = val;
  console.log("val.value", val);
}

//修改的某个角色
function onClick(item, index) {
  edit_id.value = index;
  state.editIds[index] = item.roleId;
  console.log(state.editIds, "state.editIds", edit_id.value);
}

//对已有角色进行编辑事件
function onModif(item) {
  console.log("修改某个角色", item, "id", num.value);
  const form = {
    accountId: "",
    ids: [],
  };
  console.log(orgList.value, "pppppp");
  const ids = [];
  orgList.value.forEach((i) => {
    if (i.child.length > 1) {
      i.child.forEach((val) => {
        ids.push(val.roleId);
      });
    } else {
      ids.push(i.child[0].roleId);
    }
  });

  console.log(ids, "idsidsidsids");
  form.accountId = item.accountId;
  // if (num.value == edit_id.value) {
  //
  // }
  if (ids.includes(num.value)) {
    return ElMessage({
      message: "已有该角色",
      type: "success",
    });
  }

  if (num.value != "") {
    if (num.value != state.editIds[edit_id.value]) {
      let list = ids.filter((item) => {
        if (item != state.editIds[edit_id.value]) {
          return item;
        }
      });
      console.log(list, "list");
      if (list.length > 0) {
        form.ids = [...list, num.value];
      } else {
        form.ids = [num.value];
      }
    } else {
      return ElMessage({
        message: "未进行修改",
        type: "success",
      });
    }
  }

  modifyAccountRoles(form).then((res) => {
    console.log(res, "res编辑");
    setTimeout(() => {
      getAccList(organ.value.id);
      edit.value.open = false;
    }, 200);
  });
}

function onDelete(item) {
  console.log(item, "删除某个角色");
  delAccountRole(item.id).then((res) => {
    console.log(res, "222222222222");
    ElMessage({
      message: res.msg,
      type: "success",
    });
    edit.value.open = false;
    setTimeout(() => {
      getAccList(organ.value.id);
    }, 300);
  });
}

//添加/编辑/成员
function onSubmit() {
  proxy.$refs["addRef"].validate((valid) => {
    if (valid) {
      const loadingInstance = ElLoading.service();
      if (staffForm.value.type == 1) {
        const data = {
          id: "",
          loginName: staffForm.value.account,
          realName: staffForm.value.name,
          password: staffForm.value.passwd,
          phone: staffForm.value.phone,
          email: staffForm.value.email,
          status: staffForm.value.status == true ? "1" : "2",
          employeeNo: staffForm.value.employeeNo,
        };
        addAccount(data).then((res) => {
          console.log(res, "resssss");
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: "success",
            });
            loadingInstance.close();
            getList();
            addDialog.value = false;
          } else {
            ElMessage.error(res.msg);
          }
        });
      } else {
        if (staffForm.value.name.trim() == "") {
          return ElMessage.error("成员姓名不能为空");
        }
        const data = {
          id: staffForm.value.id,
          loginName: staffForm.value.account,
          realName: staffForm.value.name,
          password: staffForm.value.passwd,
          phone: staffForm.value.phone,
          email: staffForm.value.email,
          status: staffForm.value.status == true ? "1" : "2",
          employeeNo: staffForm.value.employeeNo,
        };
        modifyAccount(data).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: "success",
            });
            addDialog.value = false;
            loadingInstance.close();
            setTimeout(() => {
              getList();
            }, 200);
          } else {
            ElMessage.error(res.msg);
          }
        });
      }
    }
  });
}

//查全部机构树
function getRoleList() {
  loading.value = true;
  queryOrgTree().then((res) => {
    state.data = res;
    loading.value = false;
  });
}

// 树组件点击选中事件
const handleNodeClick = (data) => {
  console.log(data, "data");
  // editList.value.child.forEach((item) => {
  //   item.roleName = "";
  // });
  getRolesOrgId(data.orgId);
};

function onConcel() {
  organ.value.open = false;
  accList.value = [];
}

//添加权限弹窗确定事件
function onConfirm() {
  console.log(accList.value, "6666666", organ.value.id);
  const data = {
    accountId: "",
    ids: [],
  };
  data.accountId = organ.value.id;
  accList.value.forEach((item) => {
    data.ids.push(item.role);
  });
  console.log(data, "ddadaddad");
  if (addStatus.value == 1) {
    addAccountRoles(data).then((res) => {
      console.log(res, "tianijia");
      ElMessage({
        message: res.msg,
        type: "success",
      });
      organ.value.open = false;
      addStatus.value = "";
      getList();
    });
  } else {
    organ.value.open = false;
  }
}

//状态变化
function handleChange(val) {
  console.log(val, "ssssssssss");
  let state;
  if (val.status == true) {
    state = 1;
  } else {
    state = 2;
  }
  //
  console.log(state, "statestatestate", val.id);
  editAccount(val.id, state).then((res) => {
    console.log(res, "gaibianzhuangt1");
    ElMessage({
      message: res.msg,
      type: "success",
    });
    setTimeout(() => {
      getList();
    }, 1000);
  });
}

//查询列表
function getList() {
  loading.value = true;
  const form = {
    phone: queryParams.value.phone,
    email: queryParams.value.email,
    status: "",
    pageSize: 1,
    pageCount: 10,
    login_name: queryParams.value.account,
  };
  accountList(form).then((res) => {
    console.log(res, "res列表");
    total.value = res.total_page;
    res.list.forEach((item) => {
      if (item.status == 1) {
        item.status = true;
      } else {
        item.status = false;
      }
    });
    data.tableList = res.list;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page_count = 1;
  getList();
}

/** 修改按钮操作 */
function handleEditTable(row) {
  proxy.resetForm("addRef");
  staffForm.value.type = 2;
  dialogTitle.value = "编辑成员信息";
  console.log(row, "row");
  addDialog.value = true;
  staffForm.value.account = row.login_name;
  staffForm.value.phone = row.phone;
  staffForm.value.email = row.email;
  staffForm.value.name = row.real_name;
  staffForm.value.id = row.id;
  staffForm.value.employeeNo = row.employeeNo;
  staffForm.value.status = row.status;
  // getAccList(row.id);
}
/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm("确定删除该角色吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delAccount(row.id).then((res) => {
      console.log(res, "sreesss");
      if (res.code == 200) {
        ElMessage({
          message: res.msg,
          type: "success",
        });
        getList();
      }
    });
  });
}

//成员添加机构角色
function handleAddTable(row) {
  console.log(5555, row);
  organ.value.open = true;
  organ.value.orgName = "";
  organ.value.orgName1 = "";
  organ.value.role = "";
  organ.value.role1 = "";
  organ.value.checked1 = false;
  organ.value.checked1 = false;
  organ.value.id = row.id;
  getAccList(row.id);
}

//根据账户ID查询已选角色列表
function getInfoList(id) {
  console.log("账户查询");
  listByAccId(id).then((res) => {
    console.log(res, "已有角色", orgList.value);
    if (res.length > 0) {
      state.haveOptions = res;
      isDisabled.value = true;
      orgList.value.forEach((item) => {
        item.child = [];
        state.haveOptions.forEach((val) => {
          if (item.orgId == val.orgId) {
            item.child.push(val);
          }
        });
      });
      console.log(orgList.value, "orgList.value");
    } else {
      ElMessage({
        message: "未查询到数据",
        type: "success",
      });
      organ.value.role = "";
      staffForm.value.role = "";
      isDisabled.value = false;
    }
  });
}
//查询所属机构列表
function getAccList(id) {
  console.log("查询所属机构列表");
  getAcconutList(id).then((res) => {
    console.log(res, "机构列表", res.data.length);
    if (res.data.length > 0) {
      orgList.value = res.data;
      isDisabled.value = true;
      getInfoList(id);
    } else {
      ElMessage({
        message: "未查询到数据",
        type: "success",
      });
      orgList.value = [];
      isDisabled.value = false;
      organ.value.orgName = "";
      staffForm.value.orgName = "";
    }
  });
}

//根据orgid查询机构下所有角色列表
function getRolesOrgId(id) {
  queryRolesByOrgId(id).then((res) => {
    console.log(res, "角色列表");
    state.options = res.data;
  });
}

getList();
getRoleList();
</script>
<style lang="scss" scoped>
.headline {
  background-color: #f3f3f3;
  text-align: center;
  span {
    display: block;
    padding-top: 5px;
  }
}

.my-header {
  padding-right: 30px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.list-style {
  margin-bottom: 5px;
}
.span-right {
  padding: 0 10px;
}
.box {
  display: inline-block;
  width: 25%;
  border: 1px solid #e4e7ed;
  padding: 5px;
  height: 32px;
  border-radius: 3px;
  color: #a8abb2;
  background-color: #f5f7fa;
}
.mg-left {
  display: inline-block;
  margin-left: 65px;
}
.btn {
  margin-left: 5px;
}
</style>
